﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace DiscountCoupon.Phone.Common
{
    public class Common
    {
        /// <summary>
        /// 在指定的父控件中查找指定类型的子控件。
        /// 使用方法：
        ///  private List<UIElement> imgList;
        ///  imgList = new List<UIElement>();
        ///   Common.FindChildren(this.FirstListBoxNews, typeof(Image), ref imgList);
        /// </summary>
        /// <param name="parent">父控件</param>
        /// <param name="targetType">查找类型</param>
        /// <param name="children">子空间数组</param>
        public static void FindChildren(UIElement parent, Type targetType, ref List<UIElement> children)
        {
            Common instance= new Common();
            instance.GetChildren(parent, targetType, ref children);
        }
        /// <summary>
        /// 在指定的父控件中查找指定类型的子控件
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="targetType"></param>
        /// <param name="children"></param>
        private void GetChildren(UIElement parent, Type targetType, ref List<UIElement> children)
        {
            int count = VisualTreeHelper.GetChildrenCount(parent);
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);
                    if (child.GetType() == targetType)
                    {
                        children.Add(child);
                    }
                    GetChildren(child, targetType, ref children);
                }
            }
        }

        //获取所有的子类型        
        public static List<T> FindAllChildOfType<T>(DependencyObject root) where T : class
        {
            var queue = new Queue<DependencyObject>();
            queue.Enqueue(root);
            List<T> allChild = new List<T>();
            while (queue.Count > 0)
            {
                DependencyObject current = queue.Dequeue();
                for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
                {
                    var child = VisualTreeHelper.GetChild(current, i);
                    var typedChild = child as T;
                    if (typedChild != null)
                    {
                        allChild.Add(typedChild);
                    }
                    queue.Enqueue(child);
                }
            }
            return allChild;
        }
    }
}
